<template>
  <div
    style="margin-top: 30px; margin-bottom: 30px"
    class="cardcarouselarticles_container"
    :style="{ backgroundColor: modelValue?.bgColor }"
    @mouseenter="isHover = true"
    @mouseleave="isHover = false"
  >
    <div
      class="card-carousel__wrapper"
      :class="[modelValue?.width || 'container-content-952']"
    >
      <div v-if="showCarousel && isShow">
        <Swiper
          ref="mySwiper"
          :modules="swiperModules"
          :slides-per-view="swiperOptions.slidesPerView"
          :space-between="swiperOptions.spaceBetween"
          :loop="swiperOptions.loop"
          :speed="swiperOptions.speed"
          :centered-slides="swiperOptions.centeredSlides"
          :auto-height="swiperOptions.autoHeight"
          :breakpoints="swiperOptions.breakpoints"
          class="swiper card-carousel__swiper"
          @slide-change="onSwiperSlideChange"
          @click-slide="onClickSLide"
          @swiper="onSwiperReady"
        >
          <SwiperSlide
            v-for="(item, idx) in list"
            class="swiper-slide"
            :key="`${item.key}-${idx}`"
          >
            <div class="slide-content">
              <CardArticle
                v-if="type == 'article'"
                :componentProps="item"
                :singleColumn="perChunk == 1"
              />
            </div>
          </SwiperSlide>
        </Swiper>
        <div class="mt-10 mt-md-12">
          <SlidesPagination
            :currentIndex="currentIndex"
            :count="pageCount"
            @updatePage="updatePage"
            @slidePrev="slidePrev"
            @slideNext="slideNext"
            dark
            :isLoop="isLoop"
          ></SlidesPagination>
        </div>
      </div>
      <!--  -->
      <div v-else>
        <div
          class="row row-cols-1 row-cols-md-3 row-cols-lg-4 justify-content-center"
        >
          <div
            style="margin-right: 10px"
            class="card-content"
            v-for="(item, idx) in list"
            :key="`${item.key}-${idx}`"
          >
            <CardArticle
              v-if="type == 'article'"
              :componentProps="item"
              :singleColumn="perChunk == 1"
            />
            <!-- <CardSchool v-if="type == 'school'" :modelValue="item" />
            <CardProfile
              v-if="type == 'profile'"
              :modelValue="item"
              :singleColumn="perChunk == 1"
              ref="profile"
            />
            <CardTestimonial
              v-if="type == 'testimonial'"
              :modelValue="item"
              :singleColumn="perChunk == 1"
            />
            <CardVideo
              v-if="type == 'video'"
              :modelValue="item"
              :singleColumn="perChunk == 1"
              @playVideo="openLightboxVideo(item)"
            />
            <CardPublication
              v-if="type == 'publication'"
              :modelValue="item"
              :singleColumn="perChunk == 1"
            /> -->
          </div>
        </div>
      </div>
    </div>
    <Operate
      v-if="!isPreview"
      v-model:show="isHover"
      @handle-edit="showSetting = true"
      @handle-delete="handleDelete"
      @handle-copy="handleCopy"
      @handle-paste="handlePaste"
    ></Operate>
  </div>

  <Setting
    v-if="!isPreview"
    v-model:show="showSetting"
    :data="modelValue"
  ></Setting>
</template>

<script lang="ts" setup>
// import { computed, nextTick, ref } from "vue";
import SlidesPagination from "@/common/SlidesPagination/index.vue";
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from "vue";
import { randomString } from "@/utils/common";
import Setting from "./setting.vue";
import Operate from "@/common/Operate/index.vue";
import { Swiper, SwiperSlide } from "swiper/vue";
import CardArticle from "@/common/CardArticle/index.vue";
import { Navigation, Pagination, Autoplay } from "swiper/modules";
// 导入 Swiper 样式
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";

// 定义组件名称
defineOptions({
  name: "CardCarouselArticles", // 修正组件名称
});

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },

  // 是否预览
  isPreview: {
    type: Boolean,
    default: true,
  },
});

console.log("!!!!", props.modelValue);
const emit = defineEmits([
  "update:modelValue",
  "handleDelete",
  "handleCopy",
  "handlePaste",
]);

const isHover = ref<boolean>(false);
const showSetting = ref<boolean>(false);

const handleDelete = () => {
  emit("handleDelete", props.modelValue.id);
};

const handleCopy = () => {
  emit("handleCopy", props.modelValue);
};

const handlePaste = (type: string) => {
  emit("handlePaste", type);
};

const handleInit = () => {
  // 使用模拟数据初始化文章轮播组件
  const data = {
    id: props.modelValue?.id || randomString(),
    type: "article", // 修正组件类型type == 'article'
    bgColor: props.modelValue?.bgColor || "#f8f9fa",
    width: props.modelValue?.width || "container-content-952", // 使用CSS类名而不是数字
    isLoop: props.modelValue?.isLoop ?? true,
    getDataType: false, // 使用静态数据
    list: [
      {
        key: "article-001",
        title: "探索人工智能的未来发展趋势",
        desc: "人工智能技术正在快速发展，从机器学习到深度学习，从自然语言处理到计算机视觉，AI正在改变我们的生活方式。本文将深入探讨AI技术的最新进展和未来发展方向。",
        image:
          "https://images.unsplash.com/photo-1677442136019-21780ecad995?w=800&h=600&fit=crop",
        alt: "人工智能概念图",
        date: "2024-01-15",
        time: "2024-01-15T10:30:00Z",
        labelName: "科技前沿",
        category: "technology",
        link: "/articles/ai-future-trends",
      },

      // 情况2: 使用meta数据的文章
      {
        key: "article-002",
        title: "可持续发展与绿色能源革命",
        description:
          "随着全球气候变化问题日益严重，可持续发展和绿色能源成为了全球关注的焦点。太阳能、风能等可再生能源技术正在快速发展。",
        image:
          "https://images.unsplash.com/photo-1466611653911-95081537e5b7?w=800&h=600&fit=crop",
        date: "2024-01-12",
        label: "environment",
        labelName: "科技前沿",
        category: "environment",
        link: "https://example.com/green-energy-revolution",
      },
      {
        key: "article-002",
        title: "可持续发展与绿色能源革命",
        description:
          "随着全球气候变化问题日益严重，可持续发展和绿色能源成为了全球关注的焦点。太阳能、风能等可再生能源技术正在快速发展。",
        image:
          "https://images.unsplash.com/photo-1466611653911-95081537e5b7?w=800&h=600&fit=crop",
        date: "2024-01-12",
        label: "environment",
        labelName: "科技前沿",
        category: "environment",
        link: "https://example.com/green-energy-revolution",
      },
      {
        key: "article-002",
        title: "可持续发展与绿色能源革命",
        description:
          "随着全球气候变化问题日益严重，可持续发展和绿色能源成为了全球关注的焦点。太阳能、风能等可再生能源技术正在快速发展。",
        image:
          "https://images.unsplash.com/photo-1466611653911-95081537e5b7?w=800&h=600&fit=crop",
        date: "2024-01-12",
        label: "environment",
        labelName: "科技前沿",
        category: "environment",
        link: "https://example.com/green-energy-revolution",
      },
      {
        key: "article-002",
        title: "可持续发展与绿色能源革命",
        description:
          "随着全球气候变化问题日益严重，可持续发展和绿色能源成为了全球关注的焦点。太阳能、风能等可再生能源技术正在快速发展。",
        image:
          "https://images.unsplash.com/photo-1466611653911-95081537e5b7?w=800&h=600&fit=crop",
        date: "2024-01-12",
        label: "environment",
        labelName: "科技前沿",
        category: "environment",
        link: "https://example.com/green-energy-revolution",
      },
      {
        key: "article-002",
        title: "可持续发展与绿色能源革命",
        description:
          "随着全球气候变化问题日益严重，可持续发展和绿色能源成为了全球关注的焦点。太阳能、风能等可再生能源技术正在快速发展。",
        image:
          "https://images.unsplash.com/photo-1466611653911-95081537e5b7?w=800&h=600&fit=crop",
        date: "2024-01-12",
        label: "environment",
        labelName: "科技前沿",
        category: "environment",
        link: "https://example.com/green-energy-revolution",
      },
    ], // 使用模拟的文章数据
  };
  emit("update:modelValue", data);
};

// Reactive data
const mySwiper = ref(null);
const profile = ref([]);
const currentIndex = ref(0);
const articleData = ref([]);
const dataCount = ref(0);
const isRerender = ref(false);
const isShow = ref(true);
const swiper = ref(null);
const screenWidth = ref(1024);

// Swiper modules
const swiperModules = [Navigation, Pagination, Autoplay];

// Swiper options
const swiperOptions = ref({
  centeredSlides: false,
  speed: 600,
  slidesPerView: 1,
  slidesPerGroup: 1,
  spaceBetween: 16,
  shortSwipes: true,
  longSwipesRatio: 0.3,
  loop: true,
  autoHeight: false,
  breakpoints: {
    768: {
      slidesPerView: 3,
      slidesPerGroup: 1,
      spaceBetween: 16,
      shortSwipes: false,
    },
    1024: {
      slidesPerView: 4,
      slidesPerGroup: 1,
      spaceBetween: 16,
    },
  },
});

// Screen width detection
const updateScreenWidth = () => {
  screenWidth.value = typeof window !== "undefined" ? window.innerWidth : 1024;
};

// Initialize screen width detection
onMounted(() => {
  updateScreenWidth();
  if (typeof window !== "undefined")
    window.addEventListener("resize", updateScreenWidth);
});

onUnmounted(() => {
  if (typeof window !== "undefined")
    window.removeEventListener("resize", updateScreenWidth);
});

// Computed properties
const classes = computed(() => props.modelValue?.classes ?? null);
const style = computed(() => props.modelValue?.style ?? null);
const type = computed(() => props.modelValue?.type ?? "school");
const width = computed(() => props.modelValue?.width ?? null);
const isLoop = computed(() => props.modelValue?.isLoop ?? true);

const list = computed(() => {
  if (props.modelValue?.getDataType) return articleData.value;
  return props.modelValue?.list || [];
});

const isDesktop = computed(() => screenWidth.value >= 1024);
const isTablet = computed(
  () => screenWidth.value >= 768 && screenWidth.value < 1024
);
const isMobile = computed(() => screenWidth.value < 768);

// const cardComponent = computed(() => {
//   if (!props.modelValue?.type) return null;

//   const componentMap = {
//     article: CardArticle,
//     school: CardSchool,
//     profile: CardProfile,
//     testimonial: CardTestimonial,
//     video: CardVideo,
//     publication: CardPublication,
//     circle: CardCircle,
//   };

//   return componentMap[props.modelValue.type] || null;
// });

const cardData = computed(() => {
  return props.modelValue?.data || [];
});

const cardTitle = computed(() => {
  return props.modelValue?.title || "";
});

const cardSubtitle = computed(() => {
  return props.modelValue?.subtitle || "";
});

const cardDescription = computed(() => {
  return props.modelValue?.description || "";
});

const cardLink = computed(() => {
  return props.modelValue?.link || null;
});

const cardLinkText = computed(() => {
  return props.modelValue?.linkText || "View More";
});

const perChunk = computed(() => {
  return screenWidth.value >= 768 ? (screenWidth.value >= 1024 ? 4 : 3) : 1;
});

const colMobile = computed(() => {
  return screenWidth.value < 768 ? 1 : 3;
});

const pageCount = computed(() => {
  if (props.modelValue?.getDataType) return dataCount.value;
  console.log("总页数======", list.value.length);
  return list.value.length;
});

const showCarousel = computed(() => {
  return (
    (list.value.length > 3 && screenWidth.value >= 1024) ||
    (list.value.length > 2 &&
      screenWidth.value >= 768 &&
      screenWidth.value < 1024) ||
    screenWidth.value < 768
  );
});

// Methods
const onSwiper = (swiperInstance) => {
  swiper.value = swiperInstance;
};

const onSlideChange = (swiperInstance) => {
  currentIndex.value = swiperInstance.realIndex;
};

const goToSlide = (index) => {
  if (swiper.value) {
    swiper.value.slideToLoop(index);
  }
};

const nextSlide = () => {
  if (swiper.value) {
    swiper.value.slideNext();
  }
};

const prevSlide = () => {
  if (swiper.value) {
    swiper.value.slidePrev();
  }
};

const handleVideoClick = (videoData) => {
  emit("showLightboxVideo", videoData);
};

// API methods (if needed)
const fetchData = async () => {
  if (!props.axiosInstance || !props.modelValue?.apiEndpoint) return;

  try {
    const response = await props.axiosInstance.get(
      props.modelValue.apiEndpoint
    );
    // Handle response data as needed
    return response.data;
  } catch (error) {
    console.error("Error fetching data:", error);
    return null;
  }
};

// const getData = async () => {
//   if (props.modelValue?.getDataType) {
//     let url = `/component/production/articles?category=${
//       props.modelValue.getDataType
//     }&per_page=${9}&page=${1}`;
//     if (props.modelValue.getDataType === "all")
//       url = `/component/production/articles?&per_page=${9}&page=${1}`;

//     const config = {
//       headers: {
//         website: `${process.env.website}-${$i18n.locale}`,
//       },
//     };
//     let data = await $axios.get(url, config);
//     articleData.value = data.data.data;
//     dataCount.value = articleData.value.length;
//     reRender();
//   }
// };

const onSwiperResize = () => {
  currentIndex.value = swiper.value?.realIndex ?? 0;
};

const onSwiperSlideChange = (swiperInstance) => {
  currentIndex.value = swiperInstance.realIndex;
};

const onSwiperReady = (swiperInstance) => {
  swiper.value = swiperInstance;
  if (!isRerender.value) {
    nextTick(() => {
      setTimeout(reRender, 100);
    });
  }
};

const updatePage = (idx) => {
  swiper.value?.slideToLoop(idx, 600);
};

const slidePrev = () => {
  swiper.value?.slidePrev(600);
};

const slideNext = () => {
  swiper.value?.slideNext(600);
};

const openLightboxVideo = (item) => {
  if (item.video_type == "outer") return;
  const modalList = list.value.filter((v) => v.video_type !== "outer");
  const modalIdx = modalList.findIndex((v) => v.key == item.key);
  $nuxt.$emit("showLightboxVideo", {
    idx: modalIdx,
    list: modalList,
  });
};

const onClickSLide = (index, reallyIndex) => {
  if (type.value == "profile") profile.value[reallyIndex].openLightbox();
};

const reRender = () => {
  isShow.value = false;
  nextTick(() => {
    isShow.value = true;
    swiper.value?.destroy();
    nextTick(() => {
      swiper.value?.update();
      isRerender.value = true;
    });
  });
};

// Watchers
// watch(
//   () => props.modelValue,
//   (newValue) => {
//     if (newValue) {
//       // getData();
//     }
//   }
// );

// Lifecycle hooks
onMounted(async () => {
  // getData();
  // Initialize any additional setup here
  if (props.modelValue?.autoFetch) {
    await fetchData();
  }
});

handleInit();
</script>

<style lang="scss" scoped>
.cardcarouselarticles_container {
  position: relative;
}
/* Bootstrap breakpoints converted to native CSS */
$teal-darkest: #1a1c20;
$neutral: #f5f5f5;

.card-carousel__wrapper {
  /* @include media-breakpoint-down(md) equivalent - max-width: 767.98px */
  @media (max-width: 767.98px) {
    padding-left: 0;
    padding-right: 0;
  }
}

.card-carousel__wrapper .swiper {
  width: 100%;
  height: auto;
}

.card-carousel__wrapper .swiper .swiper-slide {
  pointer-events: none;
  height: auto;
  // 移除固定宽度设置，让 Swiper 自动计算
}

@media (max-width: 767.98px) {
  .card-carousel__wrapper .swiper .swiper-slide {
    padding-left: 32px;
    padding-right: 32px;
  }
}

.card-carousel__wrapper .swiper .swiper-slide .slide-content {
  pointer-events: auto;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-carousel .row {
  --bs-gutter-x: 16px;
  --bs-gutter-y: 80px;
}

@media (max-width: 767.98px) {
  .card-carousel .row {
    --bs-gutter-y: 40px;
  }
}

.card-carousel__title {
  color: #0032A0;
  margin-bottom: 24px;
}

@media (max-width: 767.98px) {
  .card-carousel__title {
    margin-bottom: 12px;
  }
}

/* Bootstrap utility classes */
.mt-10 {
  margin-top: 2.5rem !important;
}

.mt-md-12 {
  /* @include media-breakpoint-up(md) equivalent - min-width: 768px */
  @media (min-width: 768px) {
    margin-top: 3rem !important;
  }
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-top: calc(-1 * var(--bs-gutter-y));
  margin-right: calc(-0.5 * var(--bs-gutter-x));
  margin-left: calc(-0.5 * var(--bs-gutter-x));
}

.row > * {
  flex-shrink: 0;
  width: 100%;
  max-width: 100%;
  padding-right: calc(var(--bs-gutter-x) * 0.5);
  padding-left: calc(var(--bs-gutter-x) * 0.5);
  margin-top: var(--bs-gutter-y);
}

.row-cols-1 > * {
  flex: 0 0 auto;
  width: 100%;
}

.row-cols-md-3 > * {
  /* @include media-breakpoint-up(md) equivalent - min-width: 768px */
  @media (min-width: 768px) {
    flex: 0 0 auto;
    width: 33.3333333333%;
  }
}

.row-cols-lg-4 > * {
  /* @include media-breakpoint-up(lg) equivalent - min-width: 1024px */
  @media (min-width: 1024px) {
    flex: 0 0 auto;
    width: 25%;
  }
}

.justify-content-center {
  justify-content: center !important;
}

.card-content {
  display: flex;
  flex-direction: column;
}
</style>
